package com.yhny.lykj.yuhannongye.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.longsichao.lscframe.ctrl.DataManager;
import com.longsichao.lscframe.model.LSCModel;
import com.longsichao.lscframe.net.HttpConnection;
import com.longsichao.lscframe.view.LSCToast;
import com.yhny.lykj.yuhannongye.Adapter.ShopcartExpandableListViewAdapter;
import com.yhny.lykj.yuhannongye.R;
import com.yhny.lykj.yuhannongye.app.BaseFragment;
import com.yhny.lykj.yuhannongye.app.UserConfig;
import com.yhny.lykj.yuhannongye.model.BaseModel;
import com.yhny.lykj.yuhannongye.model.CarChildModel;
import com.yhny.lykj.yuhannongye.model.CarListModel;
import com.yhny.lykj.yuhannongye.net.NetHelper;
import com.yhny.lykj.yuhannongye.tools.Tools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 购物车页面
 * Created by lc on 2017/2/1.
 */
public class CarFragment extends BaseFragment implements ShopcartExpandableListViewAdapter.CheckInterface, ShopcartExpandableListViewAdapter.ModifyCountInterface, View.OnClickListener  {

    public static CarFragment carFragment;

    private TextView leftView;

    private ExpandableListView exListView;
    private CheckBox cb_check_all;
    private TextView tv_total_price;
    private TextView tv_delete;
    private TextView tv_go_to_pay;
    private Context context;

    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量

    private ShopcartExpandableListViewAdapter selva;

    private List<CarListModel.ListEntity> carList = new ArrayList<>();
    private CarListModel carSmlpeList = new CarListModel();
    private String carId;//购物车id ，分隔

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_car, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView textView = (TextView)view.findViewById(R.id.name_top_bar);
        textView.setText("购物车");
        view.findViewById(R.id.left_group).setOnClickListener(this);
        leftView = (TextView)view.findViewById(R.id.left_text);
        leftView.setOnClickListener(this);
        leftView.setVisibility(View.GONE);
        exListView = (ExpandableListView) view.findViewById(R.id.exListView);
        cb_check_all = (CheckBox) view.findViewById(R.id.all_chekbox);
        tv_total_price = (TextView) view.findViewById(R.id.tv_total_price);
        tv_delete = (TextView) view.findViewById(R.id.tv_delete);
        tv_go_to_pay = (TextView) view.findViewById(R.id.tv_go_to_pay);
        initEvents();
        DataManager.getData(MODEL_PROCESS_0, NetHelper.Car.getCarList(1), this);
    }



    private void initEvents()
    {
        carList= new ArrayList<>();
        selva = new ShopcartExpandableListViewAdapter(carList, getContext());
        selva.setCheckInterface(this);// 关键步骤1,设置复选框接口
        selva.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
        exListView.setAdapter(selva);

        for (int i = 0; i < selva.getGroupCount(); i++)
        {
            exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
        }

        cb_check_all.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        tv_go_to_pay.setOnClickListener(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data!=null) {
            switch (resultCode){
                case FROM_TYPE_VIEW_CAR_LIST:{
                    DataManager.getData(MODEL_PROCESS_1,  NetHelper.Car.getCarList(1), this);
                    break;
                }
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public boolean onModel(int caseId, LSCModel model) {
        if (super.onModel(caseId, model)) {
            dismissProgressDialog();
            return false;
        }
        switch (caseId){
            case MODEL_PROCESS_0: {
                //购物车列表
                CarChildModel carListModel =(CarChildModel)model;
                if (isDataEmpty(carListModel)||carListModel.status!=1){

                }else{
                    if (carListModel!=null&&carListModel.list!=null) {
                        carList.clear();
                        CarListModel.ListEntity carListModel1 = new CarListModel.ListEntity();
                        carListModel1.goodslist = new ArrayList<>();
                        carList.add(carListModel1);
                        carList.get(0).goodslist.addAll(carListModel.list);
                        selva.notifyDataSetChanged();
                        for (int i = 0; i < selva.getGroupCount(); i++) {
                            exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
                        }
                    }
                }

                break;
            }

        }
        return false;
    }
    /**
     * 删除购物车
     * @param cart_id
     */
    private void delCar(String cart_id){
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("action", "delship");
        builder.addFormDataPart("userid", UserConfig.getConfigUserId());
        builder.addFormDataPart("shipid", cart_id);
        Request request = new Request.Builder().url(NetHelper.Car.delCarInfo().getUrl()).post(builder.build()).build();
        HttpConnection.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        LSCToast.show(getActivity(), "删除失败!");
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        if (!Tools.isGoodJson(string)){
                            LSCToast.show(getActivity(), "删除失败!");
                        }else {
                            Gson gson = new GsonBuilder().serializeNulls().create();
                            BaseModel userInfo = gson.fromJson(string, BaseModel.class);
                            if (userInfo == null) {
                                LSCToast.show(getActivity(), "删除失败!");
                            } else {
                                LSCToast.show(getActivity(), userInfo.msg);
                            }
                        }
                    }
                });
            }
        });

    }




    /**
     * 删除操作<br>
     * 1.不要边遍历边删除，容易出现数组越界的情况<br>
     * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
     */
    protected void doDelete()
    {
        String carid = "";
        List<CarListModel.ListEntity> toBeDeleteGroups = new ArrayList<CarListModel.ListEntity>();// 待删除的组元素列表
        for (int i = 0; i < carList.size(); i++)
        {
            CarListModel.ListEntity group = carList.get(i);
            if (group.isChoosed())
            {
                toBeDeleteGroups.add(group);
            }
            List<CarListModel.ListEntity.GoodsListEntity> toBeDeleteProducts = new ArrayList<CarListModel.ListEntity.GoodsListEntity>();// 待删除的子元素列表
            List<CarListModel.ListEntity.GoodsListEntity> childs = carList.get(i).goodslist;
            for (int j = 0; j < childs.size(); j++)
            {
                if (childs.get(j).isChoosed())
                {
                    toBeDeleteProducts.add(childs.get(j));
                    //组装 购物车id
                    if (TextUtils.isEmpty(carid)){
                        carid=childs.get(j).id;
                    }else{
                        carid = carid+","+childs.get(j).id;
                    }
                }
            }

            childs.removeAll(toBeDeleteProducts);
        }
        delCar(carid);//删除
        carList.removeAll(toBeDeleteGroups);
        selva.notifyDataSetChanged();
        calculate();
    }
    @Override
    public void onClick(View view) {
        AlertDialog alert;
        switch (view.getId())
        {
            case R.id.left_text:
            case R.id.left_group:{

                break;
            }
            case R.id.all_chekbox:
                doCheckAll();
                break;
            case R.id.tv_go_to_pay:
                if (totalCount == 0)
                {
                    Toast.makeText(getActivity(), "请选择要购买的商品", Toast.LENGTH_LONG).show();
                    return;
                }
                alert = new AlertDialog.Builder(getActivity()).create();
                alert.setTitle("操作提示");
                alert.setMessage("总计:\n" + totalCount + "种商品\n" + totalPrice + "元");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        return;
                    }
                });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        Intent intent = new Intent(getActivity(),OrderInfoActivity.class);
                        intent.putExtra(CAR_LIST_DATA,  calculateShop());
                        intent.putExtra(CAR_LIST_PRICE,  ""+totalPrice);
                        intent.putExtra(CAR_LIST_ID,  carId);
                        intent.putExtra(FROM_TYPE_ID,FROM_TYPE_VIEW_CAR_LIST);
                        startActivityForResult(intent,FROM_TYPE_VIEW_CAR_LIST);
                        return;
                    }
                });
                alert.show();
                break;
            case R.id.tv_delete:
                if (totalCount == 0)
                {
                    Toast.makeText(getActivity(), "请选择要移除的商品", Toast.LENGTH_LONG).show();
                    return;
                }
                alert = new AlertDialog.Builder(getActivity()).create();
                alert.setTitle("操作提示");
                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        return;
                    }
                });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //删除购物车
                        doDelete();
                    }
                });
                alert.show();
                break;
        }
    }

    @Override
    public void checkGroup(int groupPosition, boolean isChecked) {
        CarListModel.ListEntity group = carList.get(groupPosition);
        List<CarListModel.ListEntity> childs = carList;
        for (int i = 0; i < childs.size(); i++)
        {
            childs.get(i).setChoosed(isChecked);
        }

        if (isAllCheck()) {
            cb_check_all.setChecked(true);
        }else {
            cb_check_all.setChecked(false);
        }
        selva.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void checkChild(int groupPosition, int childPosition, boolean isChecked) {
        boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
        CarListModel.ListEntity group = carList.get(groupPosition);
        List<CarListModel.ListEntity> childs = carList;
        for (int i = 0; i < childs.size(); i++)
        {
            if (childs.get(i).isChoosed() != isChecked)
            {
                allChildSameState = false;
                break;
            }
        }
        if (allChildSameState)
        {
            group.setChoosed(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
        } else
        {
            group.setChoosed(false);// 否则，组元素一律设置为未选中状态
        }

        if (isAllCheck())
            cb_check_all.setChecked(true);
        else
            cb_check_all.setChecked(false);
        selva.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        CarListModel.ListEntity.GoodsListEntity product = (CarListModel.ListEntity.GoodsListEntity) selva.getChild(groupPosition, childPosition);
        int currentCount = product.goods_nums;
        currentCount++;
        product.goods_nums =currentCount;
        ((TextView) showCountView).setText(currentCount + "");

        selva.notifyDataSetChanged();
        calculate();
    }

    @Override
    public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked) {
        CarListModel.ListEntity.GoodsListEntity product = (CarListModel.ListEntity.GoodsListEntity) selva.getChild(groupPosition, childPosition);
        int currentCount = product.goods_nums;
        if (currentCount == 1)
            return;
        currentCount--;

        product.goods_nums = currentCount;
        ((TextView) showCountView).setText(currentCount + "");

        selva.notifyDataSetChanged();
        calculate();
    }
    private boolean isAllCheck()
    {

        for (CarListModel.ListEntity group : carList)
        {
            if (!group.isChoosed())
                return false;

        }

        return true;
    }

    /** 全选与反选 */
    private void doCheckAll()
    {
        for (int i = 0; i < carList.size(); i++)
        {
            carList.get(i).setChoosed(cb_check_all.isChecked());
            CarListModel.ListEntity group = carList.get(i);
            List<CarListModel.ListEntity.GoodsListEntity> childs = carList.get(i).goodslist;
            for (int j = 0; j < childs.size(); j++)
            {
                childs.get(j).setChoosed(cb_check_all.isChecked());
            }
        }
        selva.notifyDataSetChanged();
        calculate();
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate()
    {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < carList.size(); i++)
        {
            CarListModel.ListEntity group = carList.get(i);
            List<CarListModel.ListEntity.GoodsListEntity> childs = carList.get(i).goodslist;
            for (int j = 0; j < childs.size(); j++)
            {
                CarListModel.ListEntity.GoodsListEntity product = childs.get(j);
                if (product.isChoosed())
                {
                    totalCount++;
                    totalPrice += product.price * product.goods_nums;

                }
            }
        }
        tv_total_price.setText("" + totalPrice+"元");
        tv_go_to_pay.setText("去支付(" + totalCount + ")");
    }

    /**
     * 统计操作<br> 统计选中商品
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private String calculateShop()
    {
        String json = "";
        carSmlpeList = new CarListModel();
        carSmlpeList.list = new ArrayList<>();
        int temp = 0;
        int smlieTemp = 0;
        for (int i = 0; i < carList.size(); i++)
        {
            temp= -1;
            CarListModel.ListEntity group = carList.get(i);
            List<CarListModel.ListEntity.GoodsListEntity> childs = carList.get(i).goodslist;
            if (group.isChoosed()){
                //添加商铺内容
                CarListModel.ListEntity listEntity = new CarListModel.ListEntity();
                listEntity.setChoosed(group.isChoosed());
                temp = i;
                carSmlpeList.list.add(listEntity);
            }

            for (int j = 0; j < childs.size(); j++)
            {

                CarListModel.ListEntity.GoodsListEntity product = childs.get(j);
                if (product.isChoosed())
                {
                    //添加商品内容
                    if (temp!=i){
                        CarListModel.ListEntity listEntity = new CarListModel.ListEntity();
                        listEntity.setChoosed(group.isChoosed());
                        listEntity.goodslist = new ArrayList<>();
                        carSmlpeList.list.add(listEntity);
                        temp= i;
                    }
                    carSmlpeList.list.get(carSmlpeList.list.size()-1).goodslist.add(product);
                    if (TextUtils.isEmpty(carId)){
                        carId=childs.get(j).id;
                    }else{
                        carId = carId+","+childs.get(j).id;
                    }
                    smlieTemp++;
                }
            }
        }
        Gson gson = new Gson();
        json = gson.toJson(carSmlpeList);
        return json;
    }


    @Override
    public void onResume() {
        DataManager.getData(MODEL_PROCESS_0, NetHelper.Car.getCarList(1), this);
        super.onResume();
    }

}
